import { onMounted, reactive, ref, watch, onUnmounted } from 'vue'
import { errorHandling } from '@/api/error-handling';
import Worker from '@/hooks/worker/nibp-worker.js?worker';//
export const useScatterChart = (option: any, props: any, key1: string, key2: string) => {
  const  commonChartRef = ref()
  const state = reactive({
    tableData: [] as any[]
  })
  let oldId: any = undefined
  const highlightItem = (index: any) => {
    commonChartRef.value.dispatchAction({
      type: 'downplay',
      dataIndex: oldId
    })
    commonChartRef.value.dispatchAction({
      type: 'highlight',
      dataIndex: index
    })
    oldId = index
  }
  onMounted(() => {
    commonChartRef.value?.setOption(option)
  })
  
  const worker = new Worker(); // 开启副线程
  let start: any
  const pageLoading = ref(false)
  const getChartData = async() => {
    pageLoading.value = true
    await errorHandling(props.config.historyApi, {deviceId: props.deviceId}, res => {
      // state.tableData = res.data
      start = (new Date()).getTime()
      worker.postMessage({
        data: res.data,
        key1,
        key2
      }); 
    })
    pageLoading.value = false
  }
  watch(() => props.visible, () => {
    if(!props.visible) {
      commonChartRef.value.dispatchAction({
        type: 'downplay',
        dataIndex: oldId
      })
    } else {
      getChartData()
    }
  }, {
    immediate: true
  })
  let  chartData: any[] = []
  const setOption = () => {
    commonChartRef.value?.setOption({
      series: [
        {
          data: chartData
        }
      ]
    });
  }
  worker.onmessage = e => {
    chartData = e.data.chartData
    state.tableData = e.data.tableData
    // console.log(state.tableData)
    setOption()
    console.log((new Date()).getTime() - start)
  }
  const rowClick = (row: any) => {
    state.tableData.forEach(item => {
      if(item.id === row.id) {
        item.is_active = true
      } else {
        item.is_active = false
      }
    })
    highlightItem(row.id)
  }
  onUnmounted(() => {
    worker.terminate();
  })
  return {
    commonChartRef,
    rowClick,
    state,
    pageLoading
  }
}